package com.example.file_management.controller;

import com.example.file_management.pojo.material.Task;
import com.example.file_management.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/tasks")
@CrossOrigin(origins = "http://localhost:5173")
public class TaskController {

    private final TaskService taskService;

    @Autowired
    public TaskController(TaskService taskService) {
        this.taskService = taskService;
    }

    // 插入任务
    @PostMapping
    public ResponseEntity<?> insertTask(@RequestBody Task task) {
        try {
            int result = taskService.insertTask(task);
            if (result > 0) {
                return ResponseEntity.ok("任务插入成功, 任务ID: " + task.getTaskId());
            } else {
                return ResponseEntity.badRequest().body("任务插入失败");
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (RuntimeException e) {
            return ResponseEntity.internalServerError().body("任务插入失败，请联系管理员");
        }
    }

    // 根据任务ID查询任务
    @GetMapping("/{taskId}")
    public ResponseEntity<Task> getTaskById(@PathVariable Long taskId) {
        Task task = taskService.getTaskById(taskId);
        return task != null ? ResponseEntity.ok(task) : ResponseEntity.notFound().build();
    }

    // 查询所有任务
    @GetMapping("/all")
    public ResponseEntity<?> getAllTasks() {
        try {
            List<Task> tasks = taskService.getAllTasks();
            return tasks.isEmpty() ? ResponseEntity.noContent().build() : ResponseEntity.ok(tasks);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("获取任务失败: " + e.getMessage());
        }
    }

    // 更新任务
    @PutMapping
    public ResponseEntity<?> updateTask(@RequestBody Task task) {
        if (task.getTaskId() == null || task.getTaskId() <= 0) {
            return ResponseEntity.badRequest().body("任务ID不能为空或无效");
        }

        Task existingTask = taskService.getTaskById(task.getTaskId());
        if (existingTask == null) {
            return ResponseEntity.notFound().build();
        }

        int result = taskService.updateTask(task);
        return result > 0 ? ResponseEntity.ok("任务更新成功") : ResponseEntity.internalServerError().body("任务更新失败");
    }

    // 根据任务ID删除任务
    @DeleteMapping("/{taskId}")
    public ResponseEntity<String> deleteTask(@PathVariable Long taskId) {
        int result = taskService.deleteTask(taskId);
        return result > 0 ? ResponseEntity.ok("任务删除成功") : ResponseEntity.notFound().build();
    }
}
